var express = require('express')
var router = express.Router()
var mongoose = require('mongoose');
var Goods = require('../models/goods')

//  连接数据库
mongoose.connect('mongodb://localhost/shopping')

mongoose.connection.on("connected",function() {
    console.log('MongoDb connected success.')
})

mongoose.connection.on("error",function() {
    console.log('MongoDb connected error.')
})

mongoose.connection.on("disconnected",function() {
    console.log('MongoDb connected disconnected.')
})

//  查询商品列表数据
router.get('/list',function(req,res,next) {
    //  获取url的page和pageSize和sort信息
    //  let page = parseInt(req.param("page"))
    //  let pageSize = parseInt(req.param("pageSize"))
    //  let sort = req.param("sort")
    let page = parseInt(req.query.page)
    let pageSize = parseInt(req.query.pageSize)
    let sort = parseInt(req.query.sort)

    //  定义mongodb查询条件
    let params = {
        salePrice:{
        $gt:0
    }}

    let priceLevel = req.query.priceLevel
    var priceGt = '',priceLte = ''
    if(priceLevel != 'all'){
        switch(priceLevel) {
            case '0':priceGt = 0;priceLte = 100;break
            case '1':priceGt = 100;priceLte = 500;break
            case '2':priceGt = 500;priceLte = 1000;break
            case '3':priceGt = 1000;priceLte = 5000;break
        }
        params = {
            salePrice:{
                $gt:priceGt,
                $lte:priceLte
            }
        }
    }

    //  skip：跳过多少条数据
    //  limit：显示多少条数据
    let skip = (page-1)*pageSize
    
    //  定义模型
    let goodsModel = Goods.find(params).skip(skip).limit(pageSize)
    //  sort为1为升序，-1为降序
    goodsModel.sort({'salePrice':sort})
    goodsModel.exec(function(err,data) {
        if(err) {
            res.json({
                status: '1',
                msg: err.message
            })
        }else {
            res.json({
                status: '0',
                msg: '',
                result: {
                    count: data.length,
                    list: data
                }
            })
        }
    })
})

//  加入购物车
router.post("/addCart",function(req,res,next) {
    var userId =  req.cookies.userId
    var productId = req.body.productId;
    var User = require('../models/user')

    User.findOne({
        userId:userId
    },function(err,user) {
        if(err) {
            res.json({
                status:"1",
                msg:err.message
            })
        }else {
            // console.log("user:"+user)
            if(user) {
                //  判断商品是否存在购物车，存在则数量加1
                let goodsItem = '';
                user.cartList.forEach(function(item) {
                    if(item.productId == productId) {
                        goodsItem = item
                        item.productNum ++
                    }
                })
                if(goodsItem){
                    user.save(function(err2) {
                        if(err2) {
                            res.json({
                                status:"1",
                                msg:err2.message
                            })
                        }else {
                            res.json({
                                status:'0',
                                msg:'',
                                result:'suc'
                            })
                        }
                    })
                }else {
                    Goods.findOne({
                        productId:productId
                    },function(err,goods){
                        if(err) {
                            res.json({
                                status:"1",
                                msg:err.message
                            })
                        }else {
                            console.log(goods)
                                goods.productNum = 1;
                                goods.checked = 1;
                                user.cartList.push(goods)
                                user.save(function(err2) {
                                    if(err2) {
                                        res.json({
                                            status: '1',
                                            msg:"err2.message"
                                        })
                                    }else {
                                        res.json({
                                            status:'0',
                                            msg:'',
                                            result:'suc'
                                        })
                                    }
                                })
                        }
                    })
                }
                
            }
        }
    })
})

//  管理商品列表
router.get('/rootList',function(req,res,next) {
    let page = parseInt(req.query.page)
    let pageSize = parseInt(req.query.pageSize)
    //  跳过多少条数据
    let skip = (page-1)*pageSize
    //  定义模型
    let goodsModel = Goods.find({}).skip(skip).limit(pageSize)
    goodsModel.exec({},function(err,goods) {
        if(err) {
            res.json({
                status: '1',
                msg: err.message,
                result: ''
            })
        }else {
            res.json({
                status :'0',
                msg:'',
                result:goods
            })
        }
    })
})

//  获取商品数量
router.get('/nav',function(req,res,next) {
    var pageSize = req.query.pageSize
    Goods.count({},function(err,num) {
        if(err) {
            res.json({
                status: '1',
                msg: err.message,
                result: ''
            })
        }else {
            res.json({
                status :'0',
                msg:'',
                result: Math.ceil(num / pageSize)
            })
        }
    })

})
//  添加商品
router.post('/addProduct',function(req,res,next) {
    var param = {
        productId: req.body.productId,
        productName: req.body.productName,
        salePrice: req.body.salePrice,
        productImage: req.body.productImage
    }
    new Goods(param).save(function(err) {
        if(err) {
            res.json({
                status: '1',
                msg: err.message,
                result: ''
            })
        }else {
            res.json({
                status: '0',
                msg: '',
                result: ''
            })
        }
    })
})

//  修改商品
router.post('/EditProduct',function(req,res,next) {
    var productId = req.body.productId,
        productName = req.body.productName,
        salePrice = req.body.salePrice,
        productImage = req.body.productImage
        console.log(productId)
        Goods.update({"productId":productId},
        {$set:{
            "productId" : productId,
            "productName" : productName,
            "salePrice" : salePrice,
            "productImage" : productImage
        }},function(err) {
            if(err) {
                res.json({
                    status: '1',
                    msg: err.message,
                    result: ''
                })
            }else {
                res.json({
                    status: '0',
                    msg: '',
                    result: ''
                })
            }
        })
})

//  删除商品
router.post('/delProduct',function(req, res, next) {
    var productId = req.body.productId
    Goods.remove({productId:productId}
    ,function(err) {
        if(err) {
            res.json({
                status: '1',
                msg: err.message,
                result: ''
            })
        }else {
            res.json({
                status: '0',
                msg: '',
                result: ''
            })
        }
    })
})

module.exports = router